﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GMS.DataAccessDapper;
using GMS.IServices;
using GMS.Models.Dto;
using GMS.Models.Entity;
using GMS.Utils;

namespace GMS.Services
{
    public class PowerInfoService : IPowerInfoService
    {
        private readonly DapperUtil _dapper;

        public PowerInfoService(DapperUtil dapper)
        {
            _dapper = dapper;
        }

        public async Task<int> AddedAsync(PowerInfoDto dto)
        {
            List<PowerInfo> powerInfos = new List<PowerInfo>();
            List<string> menuIds = dto.MenuIds.Split(",").ToList();
            menuIds.ForEach(x =>
            {
                PowerInfo info = new PowerInfo();
                info.Id = GuidHelper.NewSeqGuid();
                info.RoleId = dto.RoleId;
                info.MenuId = x.ToGuid();
                EntityHelper<PowerInfo>.SetComm(info);
                powerInfos.Add(info);
            });
            //TODO:数据少的情况下可以先情况角色相关 然后再次添加
            string strSql = @"delete from PowerInfo where RoleId=@RoleId";
            await _dapper.ExecuteAsync(strSql, new { roleId = dto.RoleId });

            strSql = @"INSERT INTO dbo.PowerInfo(Id, RoleId, MenuId, CreateId, CreateBy, CreateTime)
            VALUES( @Id, @RoleId, @MenuId, @CreateId, @CreateBy, getdate())";
            return await _dapper.ExecuteAsync(strSql, powerInfos);
        }

        public async Task<Array> GetTreeKeysAsync(Guid roleId)
        {
            string strSql = "select menuId from PowerInfo where roleId=@roleId";
            var menuIds = await _dapper.QueryMultipleAsync<Guid>(strSql, new { roleId = roleId });
            return await Task.FromResult(menuIds.ToArray());
        }

    }
}